package com.hisee.main;

import com.hisee.bean.BS004;
import com.hisee.bean.BS320;
import com.hisee.readxml.ReadXml;
import com.hisee.util.DbUtil;
import com.hisee.util.SimpleStringUtil2;
import com.hisee.writedb.WriteMysql;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;
import io.minio.MinioClient;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.joda.time.DateTime;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 将xml指定内容解析到check_interface表中
 */
public class Client {

	public static final String QUEUE_MANAGER_NAME = "GWO.QM"; //接收消息队列的管理器名称
	public static final String SENDQUEUE_MANAGER_NAME = "GWI.QM"; //发送消息队列的管理器名称
	public static final String QUEUE_NAME = "OUT.S119.MSG.LQ"; //队列名称
	public static final String SEND_QUEUE_NAME = "IN.BS004.LQ"; //发送队列名称
	public static final String SNED_QUEUE2_NAME = "IN.BS320.LQ"; //发送队列2名称
	public static final String CHANNEL = "IE.SVRCONN"; //通道名
	public static final int QM_PORT = 6000; //接收消息队列端口
	public static final int SEND_QM_PORT = 5000; //发送消息队列端口
	public static final String TRACE = "trace"; //跟踪调试输出模式开关值
	//配置放到config目录
	public static final String PROPS_CONF = "config/properties_in.txt";
	public static final String JDBC_MYSQL_PROPERTIES = "config/jdbc-mysql.properties";
	public static final int NO_MSG = 2033;
    //保存的消息文件放到msg目录
    public static final String MSG_DUMP_FOLDER = "msg/";
    public static final String MSG_DUMP_FILENAME = "%s%s%s.xml";
    // 队列管理器引用
	private static String hostName;
	private static MQQueueManager queueManager;
	private static MQQueueManager sendQueueManager;
	// 队列引用
	private static MQQueue queue;
	private static MQQueue sendQueue;
	private static MQQueue sendQueue2;

	private static boolean bTrace = false;

	public static void main(String[] args) throws Exception {
        //单独打jar包，库文件放到lib目录，MANIFEST.MF中需要加上引用的jar包相对路径和名称
		if (args.length > 0) {
			String trace = args[0]; //参数1=trace表示开启跟踪调试输出模式，每次收到和发出的消息会存盘
			if (trace.equalsIgnoreCase(TRACE)) {
				bTrace = true;
				System.out.format("bTrace = %s\r\n", bTrace);
			}
		}
		try {
			Properties props = new Properties();
			props.load(new FileInputStream(PROPS_CONF));
			//从配置文件读取IBM MQ主机名
			hostName = props.getProperty("MQ_HOST_NAME");
			//TODO: 去除魔法常量如BS320,BS004,BS002,BS005
			initEnvironment(hostName);
			getMsg();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				destroyEnvironment();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * <b>应用启动时初始化队列管理器连�?/b> <br>
	 * 由于连接队列管理器如同连接数据一样，建立时需要资源较多， 连接时间较长�?因此不要每次创建关闭�?建议应用程序保持�?��
	 * 或多个队列管理器连接�? 但应用关闭时注意关闭连接，释放资源！
	 *
	 * @throws Exception
	 */
	public static void initEnvironment(String hostName) throws Exception {
		queueManager = createQueueManager(hostName, CHANNEL, QM_PORT, QUEUE_MANAGER_NAME);
		int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF
				| MQConstants.MQOO_OUTPUT | MQConstants.MQOO_FAIL_IF_QUIESCING;

		// 打开目标队列
		queue = queueManager.accessQueue(QUEUE_NAME, openOptions);

		sendQueueManager = createQueueManager(hostName, CHANNEL, SEND_QM_PORT, SENDQUEUE_MANAGER_NAME);
		openOptions = MQConstants.MQOO_BIND_AS_Q_DEF | MQConstants.MQOO_OUTPUT;

		// 打开目标队列
		sendQueue = sendQueueManager.accessQueue(SEND_QUEUE_NAME, openOptions);
		sendQueue2 = sendQueueManager.accessQueue(SNED_QUEUE2_NAME, openOptions);
	}

	private static MQQueueManager createQueueManager(String hostName, String channel, int port, String queueManagerName) throws MQException {
		Hashtable<String, Comparable> env = new Hashtable<String, Comparable>();
		// 服务器的id、名称
		env.put(MQConstants.HOST_NAME_PROPERTY, hostName);
		// 连接通道
		env.put(MQConstants.CHANNEL_PROPERTY, channel);
		// 服务器MQ服务使用的编码，1381代表GBK，1208代表UTF(Coded Character Set Identifier:CCSID)
		env.put(MQConstants.CCSID_PROPERTY, 1208);
		// 端口号
		env.put(MQConstants.PORT_PROPERTY, port);
		// 传输类型
		env.put(MQConstants.TRANSPORT_PROPERTY, MQConstants.TRANSPORT_MQSERIES);

		// 建立队列管理器连接
		return new MQQueueManager(queueManagerName, env);
	}

	/**
	 * 程序结束时释放队列管理连接资源
	 *
	 * @throws Exception
	 */
	public static void destroyEnvironment() throws Exception {
		disconnectQueueManager(queueManager);
		disconnectQueueManager(sendQueueManager);
	}

	public static void getMsg() throws Exception {

		try {
			while (true) {
				System.out.format("start retrive msg at %s\r\n", new SimpleDateFormat("yyyyMMdd_HH:mm:ss").format(Calendar.getInstance().getTime()));
				retriveNewMessageAndConsume();
				System.out.format("finish retrive msg at %s\r\n", new SimpleDateFormat("yyyyMMdd_HH:mm:ss").format(Calendar.getInstance().getTime()));
				findStatusUpdateAndSendMessage();
				findAllReportsAndSendMessage();
				if (bTrace) {
//					break;
				}
				System.out.format("bTrace = %s, sleep 5s\r\n", bTrace);
				Thread.sleep(5000);
			}
		} catch (MQException e) {
			System.out.format("e.reasonCode = %s\r\n", e.reasonCode);
			// 回滚事务
			queueManager.backout();
			if (e.reasonCode == MQConstants.MQRC_CHANNEL_NOT_AVAILABLE
					|| e.reasonCode == MQConstants.MQRC_CONNECTION_BROKEN
					|| e.reasonCode == MQConstants.MQRC_CONNECTION_ERROR
					|| e.reasonCode == MQConstants.MQRC_CONNECTION_STOPPED
					|| e.reasonCode == MQConstants.MQRC_Q_MGR_QUIESCING
					|| e.reasonCode == MQConstants.MQRC_GET_INHIBITED) {
				// 设定重新连接（接入厂商考虑重新连接设定）
				queueManager = createQueueManager(hostName, CHANNEL, QM_PORT, QUEUE_MANAGER_NAME);
				System.out.format("Queue Manager connection not available, need to create connection again! Reason: %s\r\n", e.reasonCode);
			} else
				throw e;
		} finally {
			System.out.println("enter final block");
			// 关闭队列
			closeQueue(queue);
			disconnectQueueManager(queueManager);
			// 关闭发送队列
			closeQueue(sendQueue);
			closeQueue(sendQueue2);
			disconnectQueueManager(sendQueueManager);
		}
	}

	private static void closeQueue(MQQueue queue) throws MQException {
		if (queue != null) {
			queue.close();
		}
	}

	private static void retriveNewMessageAndConsume() throws Exception {
		// 设置取消息参数属性
		MQGetMessageOptions gmo = new MQGetMessageOptions();
		gmo.options = MQConstants.MQGMO_SYNCPOINT | MQConstants.MQGMO_WAIT;

		// 设置等待时间-1 为无限等待）
		gmo.waitInterval = 1000; // 毫秒

		int i = 0;
		//每次最多处理100条消息
		while (i < 100){
			// 从队列中取出消息
			MQMessage msg = new MQMessage();
			String timeStamp;
			boolean bMessageExist = true;
			try {
				queue.get(msg, gmo);
			} catch (MQException e){
				if (e.reasonCode == NO_MSG) {
					bMessageExist = false;
					System.out.format("i = %s, breaking...\r\n", i);
					break;
				} else {
					throw e;
				}
			}

			if (bMessageExist) {
				int dataLength = msg.getDataLength();

				// 取得消息内容
				String message = msg.readStringOfByteLength(dataLength);
				timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
				System.out.format("%s: message data length: %s\r\n", timeStamp, dataLength);

				// 打印消息内容
				String msgTmpFilename = "message_in.xml";
				try (PrintWriter out = new PrintWriter(msgTmpFilename)) {
					out.println(message);
				}
				String message1 = fileAnyEncodingToString(Paths.get(msgTmpFilename));

				String requestType = ReadXml.getRequestType(message1);
				if (requestType != null && !requestType.isEmpty()) {
					// 开单申请
					if ("BS002".equals(requestType)) {
						dumpMsg(message1, "BS002", new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(Calendar.getInstance().getTime()));
						timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(Calendar.getInstance().getTime());
						System.out.format("%s: message type is BS002, insert new request\r\n", timeStamp);
						Map<String, Object> mapContent = ReadXml.parseApplyXmlToMap(message1);
						int c = WriteMysql.find(mapContent.get("examination_code").toString());
						if (c == 0) {
							WriteMysql.insert(mapContent);
						}
						System.out.println("insert done");
					}// 撤单申请
					else if ("BS005".equals(requestType)) {
						dumpMsg(message1, "BS005", new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(Calendar.getInstance().getTime()));
						timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(Calendar.getInstance().getTime());
						System.out.format("%s: message type is BS005, update old request\r\n", timeStamp);
						String doctor_advice_id = ReadXml.getDoctorAdviceId(message1);
						int c = WriteMysql.findByDoctorAdviceId(doctor_advice_id);
						if (c > 0) {
							//根据医嘱编号更新
							WriteMysql.update(doctor_advice_id, message1);
						}
						System.out.println("update done");
					}
				}
				//消耗此条消息
				queueManager.commit();
				
				//zh  begin  同时发送回传消息给江苏省人民
				
				
				i++;
				Thread.sleep(25);
			}
		}
	}

    private static void dumpMsg(String message, String msg_type, String recordTimeStamp) throws FileNotFoundException {
        if (bTrace)
            try (PrintWriter out = new PrintWriter(String.format(MSG_DUMP_FILENAME, MSG_DUMP_FOLDER, msg_type, recordTimeStamp))) {
                out.println(message);
            }
    }

    private static void findStatusUpdateAndSendMessage() throws IOException, MQException, DocumentException, InterruptedException {
		String timeStamp;List<BS004> bs004List = getDbList();
		timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(Calendar.getInstance().getTime());
		if (bs004List.size() > 0) System.out.format("%s: BS004 list size: %s\r\n", timeStamp, bs004List.size());
		int i = 0;
		for (BS004 bs004 : bs004List) {
			i += 1;
			String message = AssembBS004(bs004);
			Map<String,String> p = getMessageHeaderProperties(bs004.getRequestData());

			// 设置发送消息参数为：具有同步性，及支持事务
			MQPutMessageOptions pmo = new MQPutMessageOptions();
			pmo.options = MQConstants.MQPMO_SYNCPOINT;

			// 设置消息格式为字符串类型
			MQMessage msg = new MQMessage();
			msg.format = MQConstants.MQFMT_STRING;

			// 消息内容编码(1208:utf-8)
			msg.characterSet = 1208;
			//就诊类别domain_id, 申请科室ID apply_unit_id, 执行科室ID exec_unit_id
			setMessageHeaderProperties(msg,"46600083-8", "BS004",
					p.get("domain_id"), p.get("apply_unit_id"), "S119", p.get("exec_unit_id"), "", "");

			// 设置消息内容
			msg.writeString(message);
			// 消息放入隊列
			sendQueue.put(msg, pmo);

			WriteMysql.updateStatus(bs004.getDoctorAdviceId(), Integer.parseInt(bs004.getStatus()));
			// 提交事务
			sendQueueManager.commit();
			timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(Calendar.getInstance().getTime());
			System.out.format("%s: Send BS004 message %s success!\r\n", timeStamp, i);
			String str = SimpleStringUtil2.Bytes2HexString(msg.messageId).toLowerCase();
			System.out.format("BS004 MsgId.length: %s, MsgId: %s\r\n", str.length(), str);
            dumpMsg(message, "BS004", new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(Calendar.getInstance().getTime()));
            Thread.sleep(25);
        }
	}

	private static Document getDocumentByString(String content) throws DocumentException {
		SAXReader reader = new SAXReader();
		InputStream is = new ByteArrayInputStream(content.getBytes());
		Document document = reader.read(is);
		return document;
	}

	private static Map<String,String> getMessageHeaderProperties(String request_data) throws DocumentException {
		Map<String,String> p =new HashMap<String,String>();

		Document document =getDocumentByString(request_data);
		Element root = document.getRootElement();
		// examination_code 申请id
		Element placerGroup =root.element("controlActProcess").element("subject").element("placerGroup");
		String domain_id = placerGroup.element("componentOf1")
				.element("encounter").element("code").attributeValue("code");

		String apply_unit_id =placerGroup.element("author").element("assignedEntity").element("representedOrganization").element("id").element("item").attributeValue("extension");

		String exec_unit_id =placerGroup.element("component2").element("observationRequest").element("location").element("serviceDeliveryLocation").element("serviceProviderOrganization")
				.element("id").element("item").attributeValue("extension");

		// 就诊类别ID(01 门诊,2 急诊,0201 普通急诊,0202 急诊留观,03 住院,04 体检,0401	普通体检,0402 干保体检,05 转院)
		p.put("domain_id",domain_id);
		System.out.format("domain_id: %s\r\n", domain_id);
		// 申请科室ID
		p.put("apply_unit_id",apply_unit_id);
		System.out.format("apply_unit_id: $s\r\n", apply_unit_id);
		//执行科室ID
		p.put("exec_unit_id",exec_unit_id);
		System.out.format("exec_unit_id: %s\r\n", exec_unit_id);

		return p;
	}

	private static void setMessageHeaderProperties(MQMessage msg, String hospital_id, String service_id,
												   String domain_id, String apply_unit_id, String send_sys_id,
												   String exec_unit_id, String order_exec_id, String extend_sub_id) throws MQException {
		//医院编码
		msg.setStringProperty("hospital_id", hospital_id);
		// 消息ID
		msg.setStringProperty("service_id", service_id);
		// 就诊类别ID(01 门诊,2 急诊,0201 普通急诊,0202 急诊留观,03 住院,04 体检,0401	普通体检,0402 干保体检,05 转院)
		msg.setStringProperty("domain_id", domain_id);
		// 申请科室ID
		msg.setStringProperty("apply_unit_id", apply_unit_id);
		// 发送系统ID
		msg.setStringProperty("send_sys_id", send_sys_id);
		// 执行科室ID
		msg.setStringProperty("exec_unit_id", exec_unit_id);
		// 医嘱执行分类编码
		msg.setStringProperty("order_exec_id", order_exec_id);
		// 扩展码（empi使用时放入域ID，其它系统标0）
		msg.setStringProperty("extend_sub_id", extend_sub_id);
	}

	private static void findAllReportsAndSendMessage() throws Exception {
		String timeStamp;
		int i;List<BS320> list =DbUtil.findAllReportToSent();
		timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(Calendar.getInstance().getTime());
		if (list.size() > 0) System.out.format("%s: BS320 list size: %s\r\n", timeStamp, list.size());
		i = 0;
		for(BS320 bs320:list)
		{
			i += 1;
			String result = downloadFile(bs320.getFileS3Key());
			String message =AssembBS320(result, bs320);
			Map<String,String> p = getMessageHeaderProperties(bs320.getRequestData());

			// 设置发送消息参数为：具有同步性，及支持事务
			MQPutMessageOptions pmo = new MQPutMessageOptions();
			pmo.options = MQConstants.MQPMO_SYNCPOINT;

			// 设置消息格式为字符串类型
			MQMessage msg1 = new MQMessage();
			msg1.format = MQConstants.MQFMT_STRING;

			// 消息内容编码(1208:utf-8)
			msg1.characterSet = 1208;
			//就诊类别domain_id, 申请科室ID apply_unit_id, 执行科室ID exec_unit_id
			setMessageHeaderProperties(msg1,"46600083-8", "BS320",
					p.get("domain_id"), p.get("apply_unit_id"), "S119", p.get("exec_unit_id"), "", "");

			// 设置消息内容
			msg1.writeString(message);
			// 消息放入隊列
			sendQueue2.put(msg1, pmo);

			WriteMysql.updateStatusByS3Key(bs320.getFileS3Key(), 1);
			// 提交事务
			sendQueueManager.commit();
			timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(Calendar.getInstance().getTime());
			System.out.format("%s: Send BS320 message seq %s success!\r\n", timeStamp, i);
			String str = SimpleStringUtil2.Bytes2HexString(msg1.messageId).toLowerCase();
			System.out.format("BS320 MsgId.length: %s, MsgId: %s\r\n", str.length(), str);
            dumpMsg(message, "BS320", new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(Calendar.getInstance().getTime()));
            Thread.sleep(25);
        }
	}

	public static String fileAnyEncodingToString(Path path) throws IOException {
		byte[] byteData = Files.readAllBytes(path);
		CharsetDetector detector = new CharsetDetector();

		String unicodeData = detector.getString(byteData, null);
		CharsetMatch match = detector.detect();
		if (match != null && match.getConfidence() > 60) {
			String encoding = match.getName();
			String lang = match.getLanguage() == null? "": match.getLanguage();
			System.out.format("%s encoding: %s language: %s\r\n", path.getFileName(), encoding, lang);
		}
		return unicodeData;
	}

	/**
	 * 拼装xml格式字符串
	 *
	 */
	public static String AssembBS320(String base64,BS320 bs320) {

		// 创建SAXReader对象
		SAXReader reader = new SAXReader();
		// 读取文件 转换成Document
		Document document = null;

		try {

			////////////////////////////////////////////////////////////////////////////////////////////////
			document = reader.read(new File("config/BS320.xml"));
			Element root = document.getRootElement();
			DateTime dt = new DateTime();
			//生效时间
			root.element("effectiveTime").attribute("value").setText(dt.toString("yyyyMMddHHmmss",Locale.CHINESE));
			Iterator<Element> id = root.element("recordTarget").element("patientRole").elementIterator("id");
			id.next();
			id.next().attribute("extension").setText(bs320.getPatientCode());
			id.next().attribute("extension").setText(bs320.getVisitNo());
			Iterator<Element> component = root.element("component").element("structuredBody").elementIterator("component");
			component.next();
			Iterator<Element> entry = component.next().element("section").elementIterator("entry");
			entry.next();
			Iterator<Element> entryRelationship = entry.next().element("organizer").element("component").element("observation").elementIterator("entryRelationship");
			entryRelationship.next();

			//媒体类型
			Element obMedia =entryRelationship.next().element("observationMedia").element("value");
			obMedia.attribute("mediaType").setText("application/pdf");;

			//媒体文本
			obMedia.setText(base64);
//			obMedia.setText("");

			return document.asXML();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	/**
	 *
	 * @param key
	 * @return
	 */
	public static String downloadFile(String key) {
		Properties props = new Properties();
		try {
			props.load(new FileInputStream(PROPS_CONF));

			String MINIO_SERVER_ADDR = props.getProperty("MINIO_SERVER_ADDR");
			String ACCESS_KEY = props.getProperty("ACCESS_KEY");
			String SECRET_KEY = props.getProperty("SECRET_KEY");
			String BUCKET_NAME = props.getProperty("BUCKET_NAME");
			String FILE_NAME = props.getProperty("FILE_NAME");

			File file = new File(FILE_NAME);
			file.delete();

			MinioClient minioClient = new MinioClient(MINIO_SERVER_ADDR, ACCESS_KEY, SECRET_KEY);

			minioClient.statObject(BUCKET_NAME, key);// 9c08203493e5edb73794257b2505ae80
			System.out.format("MINIO_SERVER_ADDR: %s, FILE_NAME: %s\r\n", MINIO_SERVER_ADDR, FILE_NAME);
			minioClient.getObject(BUCKET_NAME, key, FILE_NAME); // "14bc898909312cb0fee3df928362ecfb"
			System.out.println("File downloaded");

			String result = encodeBase64File(FILE_NAME);
			return result;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";

	}

	/**
	 *
	 * @param path
	 *            文件路径
	 * @return BASE64编码后的字符串
	 * @throws Exception
	 *             抛出异常
	 */
	public static String encodeBase64File(String path) throws Exception {
		File file = new File(path);
		FileInputStream inputFile = new FileInputStream(file);
		byte[] buffer = new byte[(int) file.length()];
		inputFile.read(buffer);
		inputFile.close();
		return new BASE64Encoder().encode(buffer);
	}

	/**
	 * check_interface (status - mq_status)如果大于0说明是待发的记录
	 *
	 */
	public static List<BS004> getDbList() {
		try {
			return DbUtil.findAllBeSent();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public static String AssembBS004(BS004 bs004) {
		// 创建SAXReader对象
		SAXReader reader = new SAXReader();
		// 读取文件 转换成Document
		Document document = null;

		try {
			document = reader.read(new File("config/BS004.xml"));
			Element root = document.getRootElement();

			Element placerGroup2 = root.element("controlActProcess").element("subject").element("placerGroup");
			Iterator<Element> patient2 = placerGroup2.element("subject").element("patient").element("id")
					.elementIterator("item");
			patient2.next();
			// 患者ID
			patient2.next().attribute("extension").setText(bs004.getPatientCode());

			// 就诊号
			patient2.next().attribute("extension").setText(bs004.getVisitNo());

			/** 操作时间 */
			placerGroup2.element("performer").element("time").element("any").attribute("value")
					.setText(bs004.getOperTime());

			/** 执行医生编码 */
			placerGroup2.element("performer").element("assignedEntity").element("id").element("item")
					.attribute("extension").setText(bs004.getOperCode());

			/** 执行医生姓名 */
			placerGroup2.element("performer").element("assignedEntity").element("assignedPerson").element("name")
					.element("item").element("part").attribute("value").setText(bs004.getOperName());

			/** 执行科室编码 */
			placerGroup2.element("location").element("serviceDeliveryLocation").element("serviceProviderOrganization")
					.element("id").element("item").attribute("extension").setText(bs004.getKsCode());

			/** 执行科室名称 */
			placerGroup2.element("location").element("serviceDeliveryLocation").element("serviceProviderOrganization")
					.element("name").element("item").element("part").attribute("value").setText(bs004.getKsName());

			/** 医嘱号 */
			placerGroup2.element("component2").element("observationRequest").element("id").element("item")
					.attribute("extension").setText(bs004.getDoctorAdviceId());

			/** 修改医嘱执行编码 */
			placerGroup2.element("component2").element("observationRequest").element("component1")
					.element("processStep").element("code").attribute("code").setText(bs004.getDoctorAdviceCode());

			/** 修改医嘱执行名称 */
			placerGroup2.element("component2").element("observationRequest").element("component1")
					.element("processStep").element("code").element("displayName").attribute("value")
					.setText(bs004.getDoctorAdviceName());

			// document转换为String字符串
			return document.asXML();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	private static void disconnectQueueManager(MQQueueManager mgr) throws Exception {
		if (mgr != null) {
			mgr.disconnect();
		}
	}

}
